package com.gcph.zhuoba.player.activitys;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.VideoView;

import com.gcph.zhuoba.R;
import com.gcph.zhuoba.main.activitys.ResourceInputActivity;
import com.gcph.zhuoba.main.bean.Resource;
import com.gcph.zhuoba.main.bean.ResourceData;
import com.gcph.zhuoba.main.bean.SocketData;
import com.gcph.zhuoba.main.common.BaseActivity;
import com.gcph.zhuoba.main.common.CommonVedioActivity;
import com.gcph.zhuoba.main.common.Constant;
import com.gcph.zhuoba.player.client.PlayerPracticeClient;
import com.gcph.zhuoba.util.L;
import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

/**
 * 会员练习的activity
 * @author Administrator
 */
public class PlayerPracticeActivity extends BaseActivity {
	//退出
    private Button btn_practice_quit;
    private Button btn_practice_revideo;
    private Button btn_practice_upload;
    private Button btn_practice_full_screnn;
    private Button btn_practice_publish;
    
    private ProgressBar pro_progressbar_upload;
    
    //线路开关
    private ToggleButton btn_practice_line;
    private Resource resource;
    private static Handler socketHandler;
    private PlayerPracticeClient socketClient;
    
    //教案视频和练习视频
    private VideoView teachVideoView;
    private VideoView practiceVideoView;
    private String practiceVideoUrl;
    
    private int videoFileId;
	private String videoFileUrl;
    
    @SuppressLint("SimpleDateFormat")
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
    
    
    // 接收进度
 	public static void acceptRate(Message rate) {
 		socketHandler.sendMessage(rate);
 	}
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.fullScreen(true);
		setContentView(R.layout.activity_player_practice);
		Intent intent = this.getIntent(); 
		//得到当前教案的详细信息
		resource=(Resource)intent.getSerializableExtra("resource");
		viewInitAndSetClickListener();
		
		L.d("resource.getVideoFileUrl==="+resource.getVideoFileUrl());
		L.d("resource.getResourceData==="+resource.getResourceData());
		
		socketClient = PlayerPracticeClient.getInstance();
		
		socketHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
            	//配对失败
            	if(PlayerPracticeClient.PAIR_FAIL == msg.what)
            	{
            		Toast.makeText(PlayerPracticeActivity.this, "与终端配对失败", Toast.LENGTH_SHORT).show();
            		finish();
            	}
            	//配对成功
            	if(PlayerPracticeClient.PAIR_SUCC == msg.what)
            	{
            		//调用我要练习指令
            		doPractice(Constant.SOCKET_METHOD_PLAYER_PRACTICE);
        			//不等socket反馈信息，直接提示
        			Toast.makeText(PlayerPracticeActivity.this, "请按桌面提示进行操作", Toast.LENGTH_LONG).show();
            	}
            	
            	//更新上传进度条
            	if (PlayerPracticeClient.VEDIO_UPLOAD_RATE.equals(msg.what) && null != msg.obj) {
					int rate = 0;
					try {
						rate = Integer.parseInt((String) msg.obj);
					} catch (Exception e) {
						e.printStackTrace();
					}
					L.d("rate==" + rate);
					pro_progressbar_upload.setProgress(rate);
				}

				// 视频上传成功
				if (PlayerPracticeClient.VEDIO_UPLOAD_SUCCESS.equals(msg.what)) {
					L.d("上传成功");
					pro_progressbar_upload.setProgress(50);
					btn_practice_full_screnn.setEnabled(true);
					SocketData socketData = (SocketData) msg.obj;
					if (null != socketData) {
						videoFileId = socketData.getFileid();
						videoFileUrl = socketData.getUrl();
						practiceVideoView.setBackgroundDrawable(null);
						practiceVideoUrl = videoFileUrl;
						
						downLoadVedio(practiceVideoUrl);
					}
					Toast.makeText(PlayerPracticeActivity.this, "上传成功", Toast.LENGTH_LONG).show();
				}
            }
		};
		
		
		//----------------------配对开始----------------------------
		new Thread(new Runnable() {
			@Override
			public void run() {
				String socket_ip = getResources().getString(R.string.socket_ip);
				int socket_port = Integer.parseInt(getResources().getString(R.string.socket_port));
				socketClient.setUpConnection(socket_ip,socket_port,socketHandler);
				L.d("======请求配对=====");
				socketClient.send("{\"method\":\"102\",\"deviceid\":\"1\",\"username\":\"test\"}");
				socketClient.handleReceive(socketHandler);
			}
		}).start();
		//----------------------配对结束----------------------------
		
	}
	
	private void doPractice(final Integer method)
	{
		new Runnable() {
			@Override
			public void run() {
				if(null != resource && null !=resource.getResourceData())
				{
					ResourceData rd = new Gson().fromJson(resource.getResourceData(), ResourceData.class);
					//{"ballsPositionData":"13:0.92715,0.02632:2|16:0.27483,0.35526|7:0.79470,0.81250:5|4:0.34603,0.90461|6:0.38742,0.90132:4,5|qd:2|TAR:13|K:7|TYPE:2","ballPower":47,"jiasaiX":0.26442307,"jiasaiY":-0.1298077}
					final String fileTime = sdf.format(new Date());
	            	final String practiceNo = "practice_"+fileTime;
	                int power=0;
	                double jiasaiX=0;
	                double jiasaiY=0;
	                try{
	                	power = rd.getBallPower();
	                	jiasaiX = rd.getJiasaiX()/2.0+0.5;
	                	jiasaiY = rd.getJiasaiY()/2.0+0.5;
	                }catch(Exception e)
	                {
	                	e.printStackTrace();
	                }
	                
					StringBuilder sb = new StringBuilder();
					sb.append("{\"method\":\"");
					sb.append(method);
					sb.append("\",\"no\":\"");
					sb.append(practiceNo);
					sb.append("\",\"data\":\"");
					sb.append(rd.getBallsPositionData());
					sb.append("\",\"line\":\"");
					sb.append(resource.getResourceLine());
					sb.append("\",\"jiasaiX\":\"");
					sb.append(jiasaiX);
					sb.append("\",\"jiasaiY\":\"");
					sb.append(jiasaiY);
					sb.append("\",\"power\":\"");
					sb.append(power);
					sb.append("\"}");
					
					socketClient.send(sb.toString());
				}
			}
		}.run();
	}
	
	/**
	 * 
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(resultCode == 0){
			if(null != socketClient)
			{
				socketClient.exit();
			}
			finish();
        } 
		
		if(resultCode == 1){
			
        }
    }
	
	private void viewInitAndSetClickListener()
	{
		//=====================初始化教案视频开始=====================
		teachVideoView = (VideoView) this.findViewById(R.id.teach_video_view);
		
		//下载视频播放
		downLoadVedio(this, teachVideoView, resource.getVideoFileUrl());
//		teachVideoView.setVideoURI(Uri.parse(getResources().getString(R.string.server_root_url) + resource.getVideoFileUrl()));
//		MediaController mediaco = new MediaController(this);
//		teachVideoView.setMediaController(mediaco);
//		mediaco.setMediaPlayer(teachVideoView);
//		teachVideoView.seekTo(1);
		//=====================初始化教案视频结束===========================
		
		practiceVideoView = (VideoView) this.findViewById(R.id.practice_video_view);
		btn_practice_full_screnn = (Button) this.findViewById(R.id.btn_practice_full_screnn);
		//========================测试视频开始 
		if(Constant.IS_DEBUG)
		{
			practiceVideoView.setBackgroundDrawable(null);
			btn_practice_full_screnn.setEnabled(true);
			practiceVideoUrl = "test.mp4";
			practiceVideoView.setVideoURI(Uri.parse(getResources().getString(R.string.server_root_url)+practiceVideoUrl));
			MediaController mediacoTest = new MediaController(PlayerPracticeActivity.this);
			practiceVideoView.setMediaController(mediacoTest);
			mediacoTest.setMediaPlayer(practiceVideoView);
			practiceVideoView.seekTo(1);
		}
		//========================测试视频结束
		
		pro_progressbar_upload = (ProgressBar) this.findViewById(R.id.pro_progressbar_upload);
	    btn_practice_quit = (Button) this.findViewById(R.id.btn_practice_quit);
	    btn_practice_revideo = (Button) this.findViewById(R.id.btn_practice_revideo);
	    btn_practice_upload = (Button) this.findViewById(R.id.btn_practice_upload);
	    btn_practice_publish = (Button) this.findViewById(R.id.btn_practice_publish);
	    btn_practice_line = (ToggleButton) this.findViewById(R.id.btn_practice_line);
	    
	    btn_practice_quit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
            	//退出断开连接
            	socketClient.exit();
            	finish();
            }
        });
	    
	    //重新练习
	    btn_practice_revideo.setOnClickListener(new View.OnClickListener() {
	    	@Override
	    	public void onClick(View arg0) {
	    		doPractice(Constant.SOCKET_METHOD_PLAYER_REPRACTICE);
	    		boolean isChecked = btn_practice_line.isChecked();
	    		if(isChecked)
	    		{
	    			socketClient.send("{\"method\":\"" + Constant.SOCKET_METHOD_PRACTICE_LINE_SWITCH + "\",\"data\":\"on\"}");
	    		}
	    	}
	    });
	    
	    //上传录像 
	    btn_practice_upload.setOnClickListener(new View.OnClickListener() {
	    	@Override
	    	public void onClick(View arg0) {
	    		final String curruntime = sdf.format(new Date());
	    		final String videono = "video_"+curruntime;
	    		new Runnable() {
					@Override
					public void run() {
						socketClient.send("{\"method\":\"" + Constant.SOCKET_METHOD_UPLOAD_VEDIO + "\",\"videono\":\"" + videono+ "\"}");
					}
				}.run();
	    	}
	    });
	    
	    //录像全屏
	    btn_practice_full_screnn.setOnClickListener(new View.OnClickListener() {
	    	@Override
	    	public void onClick(View arg0) {
	    		Intent intent = new Intent(PlayerPracticeActivity.this,CommonVedioActivity.class);
				intent.putExtra("videoFileUrl", practiceVideoUrl);
				startActivity(intent);
	    	}
	    });
	    
	    //去发布练习页面
	    btn_practice_publish.setOnClickListener(new View.OnClickListener() {
	    	@Override
	    	public void onClick(View arg0) {
	    		
	    		Intent intent = new Intent(PlayerPracticeActivity.this, ResourceInputActivity.class);
	    		intent.putExtra("parentResourceId",resource.getId());
				intent.putExtra("resourceType", Constant.RESOURCE_TYPE_LIANXI);
				intent.putExtra("resourceSmallType", resource.getResourceSmallType());
				
				intent.putExtra("star", resource.getStar());
				intent.putExtra("imgFileId", resource.getImgFileId());
				intent.putExtra("videoFileId", videoFileId);
				startActivityForResult(intent, 1);
	    	}
	    });
	    
	    //线路开关
	    btn_practice_line.setOnClickListener(new View.OnClickListener() {
	    	@Override
	    	public void onClick(View arg0) {
	    		final boolean checkedFlag = btn_practice_line.isChecked();
	    		new Runnable() {
					@Override
					public void run() {
						if(checkedFlag)
			    		{
							socketClient.send("{\"method\":\"" + Constant.SOCKET_METHOD_PRACTICE_LINE_SWITCH + "\",\"data\":\"on\"}");
			    		}else
			    		{
			    			socketClient.send("{\"method\":\"" + Constant.SOCKET_METHOD_PRACTICE_LINE_SWITCH + "\",\"data\":\"off\"}");
			    		}
					}
				}.run();
	    		
	    	}
	    });
	    
	}
	
	/*
	 * 下载视频，并保存到存储卡
	 */
	private void downLoadVedio(String remoteFile)
	{
		HttpUtils http = new HttpUtils();
		String url = getResources().getString(R.string.server_root_url) +remoteFile;
		String targetFile = getFileNameFromUrl(remoteFile);
		final String  target = Environment.getExternalStorageDirectory().getPath()+"/DCIM/Camera/"+targetFile;
		File file =new File(target);
		if(file.exists())
		{
			file.delete();
		}
        http.download(url, target, true, true,  
                new RequestCallBack<File>() {  
                    @Override  
                    public void onStart() {  
                    	L.d("=====开始下载=====");
                    }  

                    @Override  
                    public void onLoading(long total, long current, boolean isUploading) {  
                        super.onLoading(total, current, isUploading);  
                        
                        int rate = (int) ((double) current/ (double) total * 50);
                        rate+=50;
                        L.d("=====下载进度====="+rate);
                        Message msg_dowload= new Message();
                        msg_dowload.what=PlayerPracticeClient.VEDIO_UPLOAD_RATE;
                        msg_dowload.obj=rate+"";
                        socketHandler.sendMessage(msg_dowload);
                    }  

                    @Override  
                    public void onSuccess(ResponseInfo<File> responseInfo) { 
                    	
                    	practiceVideoView.setBackgroundDrawable(null);
                    	practiceVideoView.setVideoURI(Uri.parse(target));
						
						MediaController mediaco = new MediaController(PlayerPracticeActivity.this);
						practiceVideoView.setMediaController(mediaco);
						mediaco.setMediaPlayer(practiceVideoView);
						practiceVideoView.seekTo(1);
                    }  

                    @Override  
                    public void onFailure(HttpException error, String msg) {  
                    	
                    	 L.d("下载失败====");
                    }

                });  
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
}